from django import template
import datetime
register = template.Library()

#register.filter('rowTotal', rowTotal)
@register.filter(name = 'columnTotal')
def columnTotal(report, column):
    total = 0
    for row in report:
        value = row[column]
        try:
            total += int(value)
        except Exception:
            continue
    return total

@register.filter(name = 'columnAverage')
def columnAverage(report, column):
    total = 0
    i = 0
    for row in report:
        value = row[column]
        try:
            total += int(value)
            i+=1
        except Exception:
            continue   
    if i != 0:
        return total/i
    else:
        return 0

@register.filter(name = 'columnFreetime')
def columnFreetime(report, column):
    leftColumn, totalColumn = column.split(',')
    total = columnTotal(report, totalColumn)
    left = columnTotal(report, leftColumn)

    if total != 0:
        return left*100/total
    else:
        return 0

@register.filter(name = 'sumOthersTotal')
def sumOthersTotal(report, column):
    try:
        others = report[column]
        keys = others.keys()
        sum = 0
        for key in keys:
            sum += others[key]
        return sum
    except Exception:
        return 0

@register.filter(name = 'sumDepartmentMembersTotal')
def sumDepartmentMembersTotal(report, column):
    try:
        column, nr = column.split(',')
        members = report[column]
        
        sum = 0
        for member in members:
            sum += member[int(nr)]
        return sum
    except Exception:
        return 0
        
@register.filter(name = 'oddOrEven')
def oddOrEven(num):
    try:
        if num % 2 == 0:
            return "even"
        else:
            return "odd"
    except Exception:
        return ""
'''
includes used in menu template
'''
@register.filter(name = 'includes')
def includes(list, object):
    return object in list

@register.filter(name = 'startswith')
def startswith(str, token):
    return str.startswith(token)

@register.filter(name = 'range')
def rangeList(str):
    try:
        start,end = str.split('-')
        return range(int(start), int(end)+1)
    except Exception:
        return None

@register.filter(name = 'extractFromDate')
def extractFromDate(str, ym):
    try:
        if(str == "-" and ym == "year"):
            return datetime.datetime.today().year
        if(str == "-" and ym == "month"):
            return datetime.datetime.today().month
        year, month = str.split('-')
        if ym == "year":
            return int(year)
        else:
            return int(month)
    except Exception:
        return 0
